package com.zhejiangzhengyuan.municipal_common.utils.waterRuler;

public class ByteAndStringUtils {

  /** byte数组转hex */
  public static String byteToHex(byte[] bytes) {
    String strHex = "";
    StringBuilder sb = new StringBuilder("");
    for (byte aByte : bytes) {
      strHex = Integer.toHexString(aByte & 0xFF);
      sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示，位数不够，高位补0
    }
    return sb.toString().trim();
  }

  /** hex转byte数组 */
  public static byte[] hexToByte(String hex) {
    int m = 0, n = 0;
    int byteLen = hex.length() / 2; // 每两个字符描述一个字节
    byte[] ret = new byte[byteLen];
    for (int i = 0; i < byteLen; i++) {
      m = i * 2 + 1;
      n = m + 1;
      int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
      ret[i] = (byte) intVal;
    }
    return ret;
  }

  /** 字节数组的大小 */
  public static int getByteSize(byte[] bytes) {
    int size = 0;
    if (bytes == null || bytes.length == 0) {
      return 0;
    }
    for (byte aByte : bytes) {
      if (aByte == '\0') {
        break;
      }
      size++;
    }
    return size;
  }
}
